﻿using Joker.Model;
using Joker.View;
using Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Net.NetworkInformation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Joker {
    public partial class LoginForm : Form {
        public LoginForm() {
            InitializeComponent();
        }

        private void ExitBtn_Click(object sender, EventArgs e) {
            Close();
            Environment.Exit(0);
        }

        private void LoginForm_Load(object sender, EventArgs e) {
            CaptchaBox.Image = Captcha.getImage(CaptchaBox.Width, CaptchaBox.Height, 4);
        }

        private void pictureBox1_Click(object sender, EventArgs e) {
            textBox3.Clear();
            CaptchaBox.Image = Captcha.getImage(CaptchaBox.Width, CaptchaBox.Height, 4);
        }

        private void LoginBtn_Click(object sender, EventArgs e) {
            try {
                if (textBox3.Text != Captcha.Text) {
                    MessageBox.Show("验证码错误！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                } else {
                    if (Username.Text.Length + Password.Text.Length == 0) {
                        MessageBox.Show("请填写用户名和密码！", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    } else {
                        string SQLstr = $"SELECT * FROM [User] WHERE [Account] = '{TextData.Base64(Username.Text)}' AND [Password] = '{TextData.MD5(Password.Text)}'";
                        DataTable tmp = DBHelper.GetDataTable(SQLstr);
                        if (tmp.Rows.Count > 0) {
                            new Processor().ShowDialog();
                            Form form = new MainForm();
                            DataTransfer.Username = tmp.Rows[0][3].ToString();
                            OpenForm.NewForm(this, form);
                            Password.Clear();
                            Password.Focus();
                        } else {
                            MessageBox.Show("用户名或密码错误！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
                textBox3.Clear();
                CaptchaBox.Image = Captcha.getImage(CaptchaBox.Width, CaptchaBox.Height, 4);
            } catch(Exception E) {
                MessageBox.Show($"遇到了些错误。\n{E.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                throw E;
            }
        }

        private void Fogotten_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
            MessageBox.Show("请联系系统管理员获取帮助", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
}
